package com.czy.seed.mvc.sys.controller;

import com.alibaba.fastjson.JSONObject;
import com.czy.seed.mvc.base.controller.BaseController;
import com.czy.seed.mvc.home.controller.CommodityController;
import com.czy.seed.mvc.home.controller.EstimateController;
import com.czy.seed.mvc.home.entity.Commodity;
import com.czy.seed.mvc.home.entity.Estimate;
import com.czy.seed.mvc.home.entity.Merchant;
import com.czy.seed.mvc.home.service.CommodityService;
import com.czy.seed.mvc.home.service.EstimateService;
import com.czy.seed.mvc.home.service.MerchantService;
import com.czy.seed.mvc.sys.entity.SysRole;
import com.czy.seed.mvc.sys.entity.SysUser;
import com.czy.seed.mvc.sys.entity.SysUserRole;
import com.czy.seed.mvc.sys.service.SysAccountRoleService;
import com.czy.seed.mvc.sys.service.SysRoleService;
import com.czy.seed.mvc.sys.service.SysUserRoleService;
import com.czy.seed.mvc.sys.service.SysUserService;
import com.czy.seed.mvc.util.PrincipalUtil;
import com.czy.seed.mvc.util.Res;
import com.czy.seed.mybatis.base.QueryParams;
import org.apache.catalina.servlet4preview.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@RequestMapping("/sys/user")
public class  SysUserController extends BaseController<SysUser> {
    public static Logger logger = LoggerFactory.getLogger(SysUser.class);
    private static final String SALT = "seed";

    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SysRoleService sysRoleService;
    @Autowired
    private SysUserRoleService sysUserRoleService;
    @Autowired
    private  MerchantService merchantService;
    @Autowired
    private CommodityService commodityService;


    public Res insert(SysUser sysUser) {
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        String encodePassword = passwordEncoder.encode("000000");
        sysUser.setPassword(encodePassword);
        return super.insert(sysUser);
    }

    /**
     * 查询用户角色信息
     * @param userId 用户id
     * @return
     */
    @RequestMapping("selectRoleInfo/{userId}")
    public Res selectRoleInfo(@PathVariable("userId") long userId) {
        //查询所有角色信息
        QueryParams allroleQueryParams = new QueryParams(SysRole.class);
        allroleQueryParams.selectProperties("id", "name");
        List<SysRole> allRoles = sysRoleService.selectListByParams(allroleQueryParams);
        //查询已有角色
        QueryParams userRoleQueryParams = new QueryParams(SysUserRole.class);
        userRoleQueryParams.selectProperties("sysRoleId");
        QueryParams.Criteria userRoleCriteria = userRoleQueryParams.createCriteria();
        userRoleCriteria.andEqualTo("sysUserId", userId);
        List<SysUserRole> userRoles = sysUserRoleService.selectListByParams(userRoleQueryParams);
        Map<String, Object> resMap = new HashMap<>();
        resMap.put("allRoles", allRoles);
        resMap.put("userRoles", userRoles);
        return Res.ok(resMap);
    }

    /**
     * 保存角色
     * @param userId 用户id
     * @param roleIds 要保存的角色id数组
     * @return
     */
    @RequestMapping("/saveUserRoles")
    public Res saveUserRoles(Long userId, Long[] roleIds) {
        sysUserRoleService.saveUserRoles(userId,roleIds);
        return Res.ok();
    }

    /**
     * 删除角色
     * @param id 主键
     * @return
     */
    @RequestMapping("/deleteByPrimary/{id}")
    public Res deleteByPrimary(@PathVariable("id") long id) {
        sysUserService.deleteByPrimaryKey(id);
        return Res.ok();
    }

    //查询全部用户
    @RequestMapping("/selectUser")
    public Res selectUser(){
        Map<String, Object> pageInfo = new HashMap<String, Object>(16);
        try{
            QueryParams queryParams = new QueryParams(SysUser.class);
            List<SysUser> sysUser = sysUserService.selectListByParams(queryParams);
            pageInfo.put("sysUser",sysUser);
            logger.info("查询用户信息成功");
        }catch(Exception e){
            logger.error("查询用户信息失败");
        }
        return  Res.ok(pageInfo);
    }
    //修改用户信息
    @RequestMapping("/updateUser")
    public Res updateUser(HttpServletRequest request){
        Map<String, Object> pageInfo = new HashMap<String, Object>(16);
        try{
            String user = request.getParameter("user");
            SysUser sysUser =  JSONObject.parseObject(user,SysUser.class);
            sysUser.setUpdateDt(new Date());
            int i =  sysUserService.updateByPrimaryKey(sysUser);
            pageInfo.put("user",i);
            logger.info("用户信息修改成功："+sysUser.getName());
        }catch(Exception e){
            logger.error("用户信息修改失败");
        }
        return Res.ok(pageInfo);
    }
    //停用||启用==>用户信息
    @RequestMapping("/updateUserInformation")
    public Res blockUser(HttpServletRequest request){
        Map<String, Object> pageInfo = new HashMap<String, Object>(16);
        String user = request.getParameter("user");
        SysUser sysUser = JSONObject.parseObject(user,SysUser.class);
        try{
            if(sysUser.isEnabled()==false){
                sysUser.setEnabled(true);
            }else{
                sysUser.setEnabled(false);
            }
            int i = sysUserService.updateByPrimaryKey(sysUser);
            pageInfo.put("user",i);
            logger.info("停用成功："+sysUser.getName());
        }catch(Exception e){
            logger.error("停用失败");
        }
        return  Res.ok(pageInfo);
    }
    //新增用户信息
    @RequestMapping("/addUser")
    public Res addUser(HttpServletRequest request){

        Boolean result =  sysUserService.addUserUnit(request);
        if(result){
            return  Res.ok();
        }else{
            return  Res.error();
        }

    }
    //重置用户密码
    @RequestMapping("/resetUser")
    public Res resetUser(HttpServletRequest request){
        Map<String, Object> pageInfo = new HashMap<String, Object>(16);
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        try{
            String merchant = request.getParameter("merchant");
            String user = request.getParameter("user");
            if(user!=null){
                SysUser sysUser =  JSONObject.parseObject(user,SysUser.class);
                String pwd =  passwordEncoder.encode("000000");
                sysUser.setPassword(pwd);
                int i =  sysUserService.updateByPrimaryKey(sysUser);
                pageInfo.put("user",i);
            }else{
               Merchant merchants = JSONObject.parseObject(merchant,Merchant.class);
               SysUser sysUser = sysUserService.selectByPrimaryKey(merchants.getUserId());
               sysUser.setPassword(passwordEncoder.encode("000000"));
               int j =   sysUserService.updateByPrimaryKey(sysUser);
               pageInfo.put("sysUser",j);
            }
            logger.info("修改成功：");
        }catch(Exception e){
            logger.error("修改失败");
        }
        return Res.ok(pageInfo);
    }

    //查询登录用户
    @RequestMapping("/selectLoginUser")
    public Res selectLoginUser(HttpServletRequest request){
        Map<String, Object> pageInfo = new HashMap<String, Object>(16);
        try{

            QueryParams queryParam = new QueryParams(Merchant.class);
            QueryParams.Criteria criteria = queryParam.createCriteria();
            criteria.andEqualTo("userId",PrincipalUtil.getLoginUser().getId());
            List<Merchant> merchants = merchantService.selectListByParams(queryParam);
            pageInfo.put("loginuser",PrincipalUtil.getLoginUser());
            pageInfo.put("userRole",PrincipalUtil.getLoginUserRoles());
            pageInfo.put("merchants",merchants);
        }catch(Exception e) {
            logger.error("查询登录id错误");
        }
        return Res.ok(pageInfo);
    }

    //用户修改密码验证
    @RequestMapping("/updatePwdVerify")
    public Res updatePwdVerify(HttpServletRequest request){
        Map<String, Object> pageInfo = new HashMap<String, Object>(16);
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        try{
            CharSequence pwdNew = request.getParameter("pwd");
            String pwdOriginal = request.getParameter("originalPwd");
            boolean see = passwordEncoder.matches(pwdNew,pwdOriginal);
            pageInfo.put("pwdResult",see);
            logger.info("密码验证成功");
        }catch(Exception e){
            logger.error("密码验证失败");
        }

        return Res.ok(pageInfo);
    }
    //用户修改密码
    @RequestMapping("/updatePwd")
    public Res updatePwd(HttpServletRequest request){
        Map<String, Object> pageInfo = new HashMap<String, Object>(16);
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        try{
            String NewPwd =  passwordEncoder.encode(request.getParameter("NewPwd"));
            SysUser LoginUser =   PrincipalUtil.getLoginUser();
            LoginUser.setPassword(NewPwd);
            LoginUser.setUpdateDt(new Date());
            int i =  sysUserService.updateByPrimaryKey(LoginUser);
            pageInfo.put("pwd1",i);
            logger.info("密码修改成功");
        }catch(Exception e){
            logger.error("密码修改失败");
        }
        return Res.ok(pageInfo);
    }
    //用户管理页面采购办用户的角色分辨
    @RequestMapping("/userRoleSelect")
    public Res userRoleSelect(){
        Map<String, Object> pageInfo = new HashMap<String, Object>(16);
        try{
            //查询所有角色信息
            QueryParams queryParam = new QueryParams(SysRole.class);
            QueryParams.Criteria userRoleQueryParams = queryParam.createCriteria();
            userRoleQueryParams.andEqualTo("code","unit");
            queryParam.selectProperties("id","name");
            List<SysRole> sysRole = sysRoleService.selectListByParams(queryParam);

            //查询已有角色
            QueryParams queryParams = new QueryParams(SysUserRole.class);
            queryParams.selectProperties("sysRoleId","sysUserId");
            QueryParams.Criteria Params = queryParams.createCriteria();
            List RoleIdList  =  new ArrayList();

            for(SysRole sysRoles: sysRole){
                RoleIdList.add(sysRoles.getId());
            }

            Params.andIn("sysRoleId",RoleIdList);
            List<SysUserRole> SysUserRole =  sysUserRoleService.selectListByParams(queryParams);
            pageInfo.put("SysUserRole",SysUserRole);
            logger.info("角色信息查询成功:"+SysUserRole.get(0).getId());
        }catch(Exception e){
            logger.error("角色信息查询失败!",e);
        }
        return Res.ok(pageInfo);
    }
    //用户管理页面采购办商家查询
    @RequestMapping("/sellRoleSelect")
    public Res sellRoleSelect(){
        Map<String, Object> pageInfo = new HashMap<String, Object>(16);
        try{
            QueryParams queryParams = new QueryParams(Merchant.class);
            QueryParams.Criteria criteria = queryParams.createCriteria();
            criteria.andEqualTo("officeId",PrincipalUtil.getLoginUser().getId());
            List<Merchant> merchants = merchantService.selectListByParams(queryParams);
            logger.info("角色信息查询成功:"+merchants.get(0).getCompanyName());
            pageInfo.put("merchants",merchants);
        }catch(Exception e){
            logger.error("角色信息查询失败!");
        }
        return Res.ok(pageInfo);

    }

    //查询所有采购办信息
    @RequestMapping("/seleceOfficeUser")
    public Res seleceOfficeUser(){
        Map<String, Object> pageInfo = new HashMap<String, Object>(16);
        try{
            //查询所有角色信息
            QueryParams queryParam = new QueryParams(SysRole.class);
            queryParam.selectProperties("id");
            QueryParams.Criteria criteria = queryParam.createCriteria();
            criteria.andEqualTo("code","office");
            List<SysRole> sysRole = sysRoleService.selectListByParams(queryParam);
            //查询角色
            QueryParams queryParams = new QueryParams(SysUserRole.class);
            queryParams.selectProperties("sysUserId");
            QueryParams.Criteria userRoleQueryParams = queryParams.createCriteria();
            List RoleIdList  =  new ArrayList();
            for (SysRole Role : sysRole) {
                RoleIdList.add(Role.getId());
            }
            userRoleQueryParams.andIn("sysRoleId",RoleIdList);
            List<SysUserRole> SysUserRole =  sysUserRoleService.selectListByParams(queryParams);
            //查询采购办信息
            List sysUserIdList  =  new ArrayList();
            for (SysUserRole Role : SysUserRole) {
                sysUserIdList.add(Role.getSysUserId());
            }
            QueryParams merchantqueryParams = new QueryParams(SysUser.class);
            QueryParams.Criteria criterias = merchantqueryParams.createCriteria();
            criterias.andIn("id",sysUserIdList);
            List<SysUser> sysUsers = sysUserService.selectListByParams(merchantqueryParams);
            pageInfo.put("sysUser",sysUsers);
            logger.info("采购办信息查询成功:"+SysUserRole.get(0).getId());
        }catch(Exception e){
            logger.error("角色信息查询失败!");
        }
        return Res.ok(pageInfo);

    }
    //查询用户名称避免重复
    @RequestMapping("/userNameSelect")
    public Res userNameSelect(){
        Map<String, Object> pageInfo = new HashMap<String, Object>(16);
        QueryParams queryParams = new QueryParams(SysUser.class);
        queryParams.selectProperties("name","username");
        List<SysUser> sysUsers = sysUserService.selectListByParams(queryParams);
        pageInfo.put("sysUsers",sysUsers);
        return  Res.ok(pageInfo);
    }
    //新增采购单位信息
    @RequestMapping("/addUnitEnter")
    public Res addUnitEnter(HttpServletRequest request){
        Boolean result =  sysUserService.addUserUnit(request);
        if(result){
            return  Res.ok();
        }else{
            return  Res.error();
        }
    }
    //查询用户管理页面商家对应的用户信息
    @RequestMapping("/sell_userSelect")
    public Res sellUserSelect(Long id,Long type){
        Map<String, Object> pageInfo = new HashMap<String, Object>(16);
        QueryParams queryParams = new QueryParams(Commodity.class);
        QueryParams.Criteria criteria = queryParams.createCriteria();
        try{
            SysUser sysUser =  sysUserService.selectByPrimaryKey(id);
            if(type!=0){
                sysUser.setEnabled(false);
                sysUser.setNonLocked(false);
                sysUserService.updateByPrimaryKey(sysUser);
                criteria.andEqualTo("businessesId",type);
                List<Commodity> commodityList = commodityService.selectListByParams(queryParams);
                for(Commodity commodity : commodityList) {
                    commodity.setInstall(0);
                    commodity.setUpdteTime(new Date());
                    commodityService.updateByPrimaryKey(commodity);
                }
                return  Res.ok();
            }
            pageInfo.put("sysUser",sysUser);
            logger.info("商家对应用户信息查询成功："+sysUser.getUsername());
        }catch(Exception e){
            logger.error("商家对应用户信息查询失败！");
        }
        return  Res.ok(pageInfo);
    }
    //查询当前登录的用户信息{用于前台页面直接使用}

    @RequestMapping("/userSelect")
    public Res userSelect(){
        Map<String, Object> pageInfo = new HashMap<String, Object>(16);
        try{
            SysUser sysUser = sysUserService.selectByPrimaryKey(PrincipalUtil.getLoginUser().getId());
            pageInfo.put("sysUser",sysUser);
            logger.info("用户信息查询成功："+sysUser.getUsername());
        }catch(Exception e){
            logger.error("用户信息查询失败！");
        }
        return  Res.ok(pageInfo);
    }
    //用户管理模糊查询
    @RequestMapping("/searchLike")
    public Res search(String label,String search){
        Map<String, Object> pageInfo = new HashMap<String, Object>();
        try{
            if("用户信息".equals(label)){
                QueryParams merchantqueryParams = new QueryParams(SysUser.class);
                QueryParams.Criteria criterias = merchantqueryParams.createCriteria();
                criterias.andEqualTo("createBy",PrincipalUtil.getLoginUser().getId());
                criterias.andLike("name","%"+search+"%");
                List<SysUser> sysUsers = sysUserService.selectListByParams(merchantqueryParams);
                pageInfo.put("sysUser",sysUsers);
            }else{
                QueryParams queryParams = new QueryParams(Merchant.class);
                QueryParams.Criteria criteria = queryParams.createCriteria();
                criteria.andEqualTo("officeId",PrincipalUtil.getLoginUser().getId());
                criteria.andLike("companyName","%"+search+"%");
                List<Merchant> merchant =  merchantService.selectListByParams(queryParams);
                pageInfo.put("merchant",merchant);
            }
            logger.info("模糊查询用户信息或商家信息成功");
        }catch(Exception e){
            logger.error("模糊查询用户信息或商家信息失败");
        }

        return Res.ok(pageInfo);
    }

    //查询用户名&&帐号验证表单
    @RequestMapping("/selectUserForm")
    public Res selectUserForm(){
        Map<String, Object> pageInfo = new HashMap<String, Object>(16);
        try{
            QueryParams queryParams = new QueryParams(SysUser.class);
            queryParams.selectProperties("username");
            List<SysUser> sysUser = sysUserService.selectListByParams(queryParams);
            pageInfo.put("sysUser",sysUser);
            logger.info("查询用户信息成功");
        }catch(Exception e){
            logger.error("查询用户信息失败");
        }
        return  Res.ok(pageInfo);
    }
}














